<?php
class User_Controller{
	//Register using
	public function CheckLength($input, $type) {
		$length = strlen($input);
		if ($length == 0) {
			echo "<script language='javascript'>";
            echo "alert('".$type."不得為空');";
            echo "history.back();";
            echo "</script>";
            die();
		}
	}
	public function Register($account, $password, $password2, $name, $birth, $tel, $new_file) {
		require('../../Model/MySQL.php');
		require('../../host_config.php');
		$mysql = new MySQL();
		$link = $mysql->connect($mysql_host, $mysql_user, $mysql_password, $mysql_db);
		$account = mysql_real_escape_string($account);
		$password = mysql_real_escape_string($password);
		$password2 = mysql_real_escape_string($password2);
		$name = mysql_real_escape_string($name);
		$birth = mysql_real_escape_string($birth);
		$tel = mysql_real_escape_string($tel);
		//$new_file = mysql_real_escape_string($new_file);
		//檢查帳號是否相同
		$sql = "SELECT * FROM User WHERE account = '$account'";
		$row = $mysql->query_row($sql, $link);
		if ($row != NULL) {
			echo "<script language='javascript'>";
			echo "alert('您的帳號已經有人註冊過，請嘗試別的帳號，謝謝');";
			echo "history.back();";
			echo "</script>";
			die();
		}
		//檢查密碼是否相同
		if ($password != $password2) {
			echo "<script language='javascript'>";
			echo "alert('密碼不相同');";
			echo "history.back();";
			echo "</script>";
			die();
		}
		User_Controller::CheckLength($account, "帳號");
		User_Controller::CheckLength($password, "密碼");
		User_Controller::CheckLength($name, "姓名");
		User_Controller::CheckLength($birth, "生日");
		User_Controller::CheckLength($tel, "電話");
		$new_file = User_Controller::Upload_Pic($new_file);
		$sha_pass = hash('sha256', $password);
		$sql = "INSERT INTO User VALUES (NULL, '$account', '$sha_pass', '$name', '$new_file', '$birth', '$tel', 1)";
		$mysql->query($sql, $link);
		$sql = "SELECT uid FROM User WHERE account = '$account'";
		$row = $mysql->query_row($sql, $link);
		$_SESSION["uid"] = $row[0];
		$_SESSION["username"] = $account;
		return $row[0];
	}
	public function Upload_Pic($new_file) {
		$upload_path = "pics/";
	 	$possible = "_0123456789"."abcdefghijklmnopqrstuvwxyz"."ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	 	$temp = 0;
	    /*如果附檔名有誤$temp = 10
	    如果上傳檔案大小有誤$temp = 20
	    如上傳失敗$temp = 30*/
	    $max_size = 1*1024*1024; //限制可檔案大小為1MB
    	$limitedext = array("bmp","gif","jpg","jpeg","png");//設定可上傳的檔案類型(副檔名)
 		$str = ""; 
		while(strlen($str) < 3) {
			$str .= substr($possible, (rand() % strlen($possible)), 1);
		}
        $uploadfilename=time().$str;
        $file_name = $new_file['name'];
        $file_tmp = $new_file['tmp_name'];
        $File_Extension = explode(".", $new_file['name']);
        $File_Extension = $File_Extension[count($File_Extension)-1];
        if($file_name == NULL){
			$file = "pics/default.jpg";
        }
        else if($new_file['error'] > 0){
            echo "上傳錯誤代碼:".$_new_file['error'];
            exit;
        }
        else if(($max_size > 0) && ($new_file['size'] > $max_size)){
            echo "您上傳的檔案大小大於".$max_size."位元組";
            $temp = 20;
        }
        else if(!in_array($File_Extension,$limitedext)){
        	echo "$File_Extension <br /> $limitedext <br />";
            echo "不支援此檔案類型<br />";
            $temp = 10;
        }else {
        	if(move_uploaded_file($file_tmp, "../../".$upload_path.$uploadfilename.".".$File_Extension)){
				$file = $upload_path.$uploadfilename.".".$File_Extension;
        	}
        	else{
				$temp = 30;
        	}
        }
		//Exception
	    if ($temp == 10) {
	    	echo "<script language='javascript'>";
	    	echo "alert('副檔名有誤（只允許GIF和JPEG檔）');";
	    	echo "history.back();";
	    	echo "</script>";
	    	die();
	    }else if ($temp == 20) {
	    	echo "<script language='javascript'>";
	    	echo "alert('無法上傳，請檢查檔案是否小於400 KB');";
	    	echo "history.back();";
	    	echo "</script>";
	    	die();
	    }else if ($temp == 30) {
	    	echo "<script language='javascript'>";
	    	echo "alert('無法上傳');";
	    	echo "history.back();";
	    	echo "</script>";
	    	die();
	    }
        return $file;
	}
	//Login using
	public function CheckUser($account, $password, $ip) {
		require_once('Model/MySQL.php');
		require('host_config.php');
		$mysql = new MySQL();
		$link = $mysql->connect($mysql_host, $mysql_user, $mysql_password, $mysql_db);
		$account = mysql_real_escape_string($account);
		$password = mysql_real_escape_string($password);
		$ip = mysql_real_escape_string($ip);
		$sha_pass = hash('sha256', $password);
		//$sql = "SELECT account, pwd, active_flag, uid FROM `User` WHERE `account` = '$account' AND `pwd` = '$password'";
		$sql = "SELECT account, pwd, active_flag, uid FROM `User` WHERE `account` = '$account' AND `pwd` = '$sha_pass'";
		$row = $mysql->query_row($sql, $link);
		if ($account != NULL && $sha_pass != NULL && $account == $row[0] && $sha_pass == $row[1]) {
			if ($row[2] == 1) {
				//user
				$temp = User_Controller::check_log($ip);
				if ($temp == 1){
					User_Controller::clear_log($ip);
				}
				$_SESSION["uid"] = $row[3];
				$_SESSION["username"] = $account;
				header("location:../FaceTech/views/index.php?id=$row[3]");
				
			} elseif ($row[2] == 2) {
				//superuser
				$temp = User_Controller::check_log($ip);
				if ($temp == 1){
					User_Controller::clear_log($ip);
				}
				$_SESSION["uid"] = $row[3];
				$_SESSION["username"] = $account;
				header("location:../FaceTech/views/MaintainSystem/ManagerPage.php");    //這是我自己隨便定義的
			}else {
				//error
				header("location:../login.php");
			}
		}else {
			$number = User_Controller::log($ip);
			if ($number == 3) {
				User_Controller::clear_log($ip);
				echo "<script language=javascript> window.opener=null; window.open('','_self'); window.close();</script>";
			}
			echo "<script language='javascript'>";
			echo "alert('account and password error, please check again!');";
			echo "history.back();";
			echo "</script>";
		}
	}
	public function log($ip) {
		require_once('Model/MySQL.php');
		require('host_config.php');
		$mysql = new MySQL();
		$link = $mysql->connect($mysql_host, $mysql_user, $mysql_password, $mysql_db);
		$ip = mysql_real_escape_string($ip);
		$sql = "SELECT number FROM log WHERE ip = '$ip'";
		$row = $mysql->query_row($sql, $link);
		if ($row == NULL) {
			$sql = "INSERT INTO log VALUES(NULL, '$ip', 1)";
			$mysql->query($sql, $link);
			return 1;
		}else {
			$temp = $row[0] + 1;
			$sql = "UPDATE log set number = '$temp' WHERE ip = '$ip'";
			$mysql->query($sql, $link);
			return $temp;
		}
	}
	public function clear_log($ip) {
		require('host_config.php');
		require_once('Model/MySQL.php');
		$mysql = new MySQL();
		$link = $mysql->connect($mysql_host, $mysql_user, $mysql_password, $mysql_db);
		$ip = mysql_real_escape_string($ip);
		$sql = "DELETE FROM log WHERE ip = '$ip'";
		$result = $mysql->query($sql, $link);
	}
	public function check_log($ip) {
		require('host_config.php');
		require_once('Model/MySQL.php');
		$mysql = new MySQL();
		$link = $mysql->connect($mysql_host, $mysql_user, $mysql_password, $mysql_db);
		$ip = mysql_real_escape_string($ip);
		$sql = "SELECT * FROM log WHERE ip = '$ip'";
		$result = $mysql->query_row($sql, $link);
		if ($result == NULL)
			return 0;
		else
			return 1;
	}
}
?>